﻿using ConfExpert.Forms.Rapor.YeniYapi;
using ConfExpert.Properties;

using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;


using System;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.ImportWizards.Koliustu
{
    public partial class CafeCoton : XImportWizard
    {
        public CafeCoton()
        {
            InitializeComponent();
        }

        //her iki dosyanın ilk sütunları: COLIS	CLENTS	STYLE	TISSUS  ve	38	39	40	41	42	43	PCES

        private void CafeCoton_Load(object sender, EventArgs e)
        {
            this.FileDone += KargoFatura_FileDone;
            this.ProcessStart += KargoFatura_ProcessStart;
            this.ProcessDone += KargoFatura_ProcessDone;

            btnSave.Enabled = false;
            btnProcessFile.Enabled = true;

            gvMaster.Init("GetCCSeasons");
            gvMaster.MakeColumnInvisible("idx");
            GridMenu gm = GridManager.GetManager(gvMaster).GridMenu;
            gm.AddMenu("Seç", SatirSec, Resources.Plus_16x16, true);
            gm.AddMenu("Bırak", SatirBirak, Resources.Minus_16x16);

            emptyEditor = new RepositoryItemButtonEdit();
            emptyEditor.Buttons.Clear();
            emptyEditor.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
            gcMaster.RepositoryItems.Add(emptyEditor);

            gvMaster.CustomRowCellEdit += gvMaster_CustomRowCellEdit;
            gvMaster.ShowingEditor += gvMaster_ShowingEditor;
            gvMaster.OptionsView.EnableAppearanceOddRow = gvMaster.OptionsView.EnableAppearanceEvenRow = false;
            gvMaster.RowStyle += gridView1_RowStyle;
            gvMaster.BestFitColumns();
            txtSezon.EditValue = "H15";

            splitter.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel2;
        }

        void gvMaster_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            GridView view = sender as GridView;
            if (view.FocusedColumn.FieldName == "Sec")
                e.Cancel = true;
        }

        RepositoryItemButtonEdit emptyEditor;
        void gvMaster_CustomRowCellEdit(object sender, CustomRowCellEditEventArgs e)
        {
            if (e.Column.FieldName == "Sec" &&
                !gvMaster.GetRowCellValue(e.RowHandle, "Sec").ToBool())
                e.RepositoryItem = emptyEditor;
        }

        void gridView1_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView view = sender as GridView;
            if (e.RowHandle > -1)
            {
                if (gvMaster.GetRowCellValue(e.RowHandle, "Sec").ToBool())
                    e.Appearance.BackColor = e.Appearance.BackColor2 = Color.SkyBlue;   // Color.FromArgb(255, 192, 0);
                else
                    e.Appearance.Combine((e.RowHandle & 1) != 0 ? view.Appearance.EvenRow : view.Appearance.OddRow);
            }
        }

        private void SatirBirak(object sender, EventArgs e)
        {
            foreach (int handle in gvMaster.GetSelectedRows())
                gvMaster.SetRowCellValue(handle, "Sec", false);

            gvMaster.EndEditing();
            btnProcessFile.Enabled = gvMaster.DataTable().Select("Sec=1").Length > 0;
        }

        private void SatirSec(object sender, EventArgs e)
        {
            foreach (int handle in gvMaster.GetSelectedRows())
                gvMaster.SetRowCellValue(handle, "Sec", true);

            gvMaster.EndEditing();
            btnProcessFile.Enabled = gvMaster.DataTable().Select("Sec=1").Length > 0;
        }

        DataSet dsResult;
        void KargoFatura_ProcessStart()
        {
            dsResult = new DataSet();
        }

        void KargoFatura_ProcessDone()
        {
            string xmlS = dsResult.Tables["S"].Serialize();
            string xml37 = dsResult.Tables["37"].Serialize();
            string xmlBarkod = dsResult.Tables["Barkod"].Serialize();

            // Do not allow the user to create new files via the FolderBrowserDialog.
            //this.folderBrowserDialog1.ShowNewFolderButton = false;

            // Default to the My Documents folder.
            //folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;


            //string Path = Dialogs.SaveFile("PDF Document", "PDF Files|*.pdf");

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            DataSet dsx;
            dsx = ExecuteDataSet("GetKoliUstu2", gvMaster.GetSelectedValues("idx"), txtSezon.EditValue.ToStr(), xmlS, xml37, xmlBarkod, false);
            if (dsx.Tables.Count < 2)
                using (Barkodsuz b = new Barkodsuz(dsx.Tables[0]))
                    if (b.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                        return;
                    else
                        dsx = ExecuteDataSet("GetKoliUstu2", gvMaster.GetSelectedValues("idx"), txtSezon.EditValue.ToStr(), xmlS, xml37, xmlBarkod, true);

            {
                //KoliUstuCCYeni koli = new KoliUstuCCYeni(dsx, Path);

                //int MxRowNr = dsx.Tables[0].Compute("MAX(RowNr)", string.Empty).ToInt() / 20000;

                KoliUstuCCYeni koli;

                if (cmbModeller.EditValue.ToStr() == "Ayrı Ayrı")
                {
                    FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
                    // Set the help text description for the FolderBrowserDialog.
                    folderBrowserDialog1.Description = "Select the directory that you want to use.";

                    DialogResult result = folderBrowserDialog1.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        string folderName = folderBrowserDialog1.SelectedPath;

                        DataView view = new DataView(dsx.Tables[0]);
                        DataTable distinctValues = view.ToTable(true, "Style");
                        foreach (DataRow r in distinctValues.Rows)
                        {
                            DataSet d = dsx.Clone();
                            dsx.Tables[0].Select("Style = '" + r["Style"] + "'").CopyToDataTable(d.Tables[0], LoadOption.OverwriteChanges);
                            dsx.Tables[1].Select("Style = '" + r["Style"] + "'").CopyToDataTable(d.Tables[1], LoadOption.OverwriteChanges);

                            koli = new KoliUstuCCYeni(d, folderName + "\\" + r["Style"] + ".pdf", chkKarbel.Checked);
                        }
                    }
                }
                else
                {
                    string fileName = Dialogs.SaveFile("PDF Document", "PDF Files|*.pdf");
                    koli = new KoliUstuCCYeni(dsx, fileName, chkKarbel.Checked);
                }

                stopwatch.Stop();

                Notify((stopwatch.ElapsedMilliseconds / 1000).ToString());
                //koli.ShowPreviewDialog();

                //KoliUstuCC k = new KoliUstuCC(ds.xKoliustu, true, txtSezon.Text, chkKarbel.Checked);
                //k.ShowPreview();
                //if (!checkEdit1.Checked)
                //    reportPresenter1.View(k);
                Notify("Done.");
            }

            dsResult.Tables.Clear();

        }

        void KargoFatura_FileDone(DataSet ds, string FileName)
        {
            if (ds.Tables.Contains("S"))
                dsResult.Tables.Add(Oku(ds.Tables["S"]));
            else
                dsResult.Tables.Add("S");

            if (ds.Tables.Contains("37"))
                dsResult.Tables.Add(Oku(ds.Tables["37"]));
            else
                dsResult.Tables.Add("37");

            dsResult.Tables.Add(Oku(ds.Tables["Barkod"]));
        }

        private DataTable Oku(DataTable dt)
        {
            DataTable dtRead = new DataTable(dt.TableName);
            DataRow drCaption = dt.Rows[0];

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                dtRead.Columns.Add();
                string cap = drCaption[i].ToStr();
                if (cap != string.Empty)
                    dtRead.Columns[i].ColumnName = cap;
            }

            for (int j = 1; j < dt.Rows.Count; j++)
                dtRead.Rows.Add(dt.Rows[j].ItemArray);

            return dtRead;
        }

    }
}
